<template>
  <PageWrapper title="服务树展示">
    <div class="mt-4">
      <a-button type="primary" @click="addTopNode()" value="large">新增顶级节点</a-button>
      <a-divider style="height: 2px; background-color: #7cb305" />
    </div>
    <a-row>
      <a-col :span="8">
        <a-directory-tree
          v-if="isShow"
          :treeData="treeData"
          multiple
          v-model:expandedKeys="expandedKeys"
          v-model:selectedKeys="selectedKeys"
        >
          <template #title="{ key: treeKey, title, id, level, children }">
            <a-dropdown :trigger="['contextmenu']">
              <span>{{ title }}</span>
              <template #overlay>
                <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey, id, level, children)">
                  <a-menu-item key="1"><PlusSquareTwoTone />新增节点</a-menu-item>
                  <a-menu-item key="2"><MinusCircleTwoTone />删除节点</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
        </a-directory-tree>
      </a-col>
    </a-row>
    <StreeDrawer @register="registerDrawer" @success="handleSuccess" />
  </PageWrapper>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
import { PageWrapper } from '/@/components/Page';
import { PlusSquareTwoTone, MinusCircleTwoTone } from '@ant-design/icons-vue';
import { deleteStreeNode, getStreeNodeList } from "@/api/demo/system";
import StreeDrawer from "@/views/stree/stree/StreeDrawer.vue";
import { useDrawer } from "@/components/Drawer";
import { useMessage } from "@/hooks/web/useMessage";

export default defineComponent({
  name: 'ServiceTreeIndex',
  components: {
    StreeDrawer,
    PageWrapper,
    PlusSquareTwoTone,
    MinusCircleTwoTone,
  },
  setup() {
    const isShow = ref(false);
    const treeData = ref([]);
    const expandedKeys = ref<string[]>(['0-0', '0-1']);
    const selectedKeys = ref<string[]>([]);
    const [registerDrawer, { openDrawer }] = useDrawer();

    // 获取服务树节点数据
    const fetchTreeData = async () => {
      try {
        const res = await getStreeNodeList();
        treeData.value = res;
        isShow.value = true;
      } catch (error) {
        console.error('获取服务树节点失败', error);
      }
    };

    // 初始化加载树数据
    fetchTreeData();

    // 添加顶级节点
    const addTopNode = async (): Promise<void> => {
      openDrawer(true, {
        level: 1,
        pid: 0,
      });
    };

    // 操作成功后的回调
    const handleSuccess = () => {
      // 操作成功后重新获取最新的树节点数据
      fetchTreeData();
    };

    const onContextMenuClick = (treeKey: string, menuKey: string, id: number, level: number, children: any) => {
      const { createMessage } = useMessage();
      if (menuKey == "1") {
        // 新增节点
        openDrawer(true, {
          level: level + 1,
          pid: id,
          title: treeKey,
        });
      } else if (menuKey == "2") {
        // 只允许删除叶子节点
        if (children && children.length > 0) {
          createMessage.error("禁止删除非叶子节点");
          return;
        }
        // 删除节点
        deleteStreeNode(id)
          .then(() => {
            createMessage.success(`已成功删除节点 ${treeKey} id=${id}`);
            // 删除成功后重新获取最新的树节点数据
            fetchTreeData();
          })
          .catch(() => {
            createMessage.error(`删除节点失败 ${treeKey} id=${id}`);
          });
      }
    };

    return {
      treeData,
      isShow,
      onContextMenuClick,
      expandedKeys,
      selectedKeys,
      registerDrawer,
      addTopNode,
      handleSuccess,
    };
  },
});
</script>
